<template>
  <el-dialog :title="action === 'add' ? '新增' : '修改'" width="30%" draggable
               :close-on-click-modal="false" v-model="visible" @open="submitted = false">
    <el-form :model="dataForm" :rules="dataRule" ref="dataFormRef" @keyup.enter.native="dataFormSubmit(dataFormRef)" label-width="80px">
      <el-form-item label="父级分类">
        <el-input v-model="dataForm.pname" readonly />
      </el-form-item>
      <el-form-item label="分类名称" prop="name">
        <el-input v-model="dataForm.name" minlength="2" maxlength="20" show-word-limit placeholder="分类名称" />
      </el-form-item>
      <el-form-item label="分类层级" prop="level">
        <el-input-number v-model="dataForm.level" :min="1" :max="3" label="分类层级" :disabled="true" />
      </el-form-item>
      <el-form-item label="是否显示" prop="visible">
        <el-switch v-model="dataForm.visible" />
      </el-form-item>
      <el-form-item label="分类排序" prop="sort">
        <el-input-number v-model="dataForm.sort" :min="1" :max="10000" label="分类排序" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="ad-footer">
        <el-button @click="visible = false">取消</el-button>
        <el-button type="primary" @click="dataFormSubmit(dataFormRef)" :disabled="submitted">确定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import http from "@/utils/httpRequest";
import validate from "@/utils/validate";
import type { FormInstance } from "element-plus";
import { ref, reactive, nextTick, defineExpose, defineEmits } from "vue";

// 操作：add-新增，update-修改
const action = ref("");

// 弹窗是否显示
const visible = ref(false);

// 提交按钮是否禁用
const submitted = ref(false);

// 表单数据
const dataForm = reactive({
  id: undefined,
  pid: undefined,
  pname: undefined,
  name: undefined,
  visible: false,
  level: 1,
  sort: 1,
});

// 表单数据校验
const dataRule = reactive({
  name: validate.required("分类名称"),
});

// 表单引用
const dataFormRef = ref<FormInstance>();

// 父级组件的自定义事件
const emit = defineEmits(['initCategoryData']);

// 表单初始化
const initForm = async (a, n) => {
  action.value = a;
  // 新增跟节点
  if (a === "add-root") {
    visible.value = true;
    await nextTick();
    dataForm.id = undefined;
    dataForm.pid = undefined;
    dataForm.pname = "跟节点";
    dataForm.level = 1;
    dataForm.sort = n && n.length > 0 && n[n.length - 1].sort + 1;
    return;
  }
  // 新增子节点操作
  if (a === "add-node") {
    // 新增表单初始化
    visible.value = true;
    await nextTick();
    dataForm.id = undefined;
    dataForm.pid = n && n.id;
    dataForm.pname = n && n.name;
    dataForm.level = n && n.attributes && n.attributes.level + 1;
    dataForm.sort = n.children && n.children.length > 0 && n.children[n.children.length - 1].sort + 1;
    return;
  }
  // 修改操作
  dataForm.id = n.id;
  http
  .post({
    url: "/product/category/info",
    params: { categoryId: dataForm.id },
  }).then(async ({ data }) => {
    if (http.success(data)) {
      visible.value = true;
      await nextTick();
      dataFormRef.value.resetFields();
      dataForm.id = data.body.id;
      dataForm.pid = data.body.pid;
      dataForm.name = data.body.name;
      dataForm.pname = data.body.pname;
      dataForm.level = data.body.level;
      dataForm.sort = data.body.sort;
      dataForm.visible = data.body.visible === 1;
    }
  });
};

// 表单提交
const dataFormSubmit = (form: FormInstance | undefined) => {
  if (submitted.value) {
    return;
  }
  form.validate((valid) => {
    if (valid) {
      submitted.value = true;
      http
        .post({
          url: `/product/category/save`,
          data: {
            id: dataForm.id || undefined,
            pid: dataForm.pid || undefined,
            name: dataForm.name,
            visible: dataForm.visible ? 1 : 0,
            sort: dataForm.sort,
            level: dataForm.level,
          },
        })
        .then(({ data }) => {
          if (http.success(data, true, true)) {
            visible.value = false;
            emit("initCategoryData");
            return;
          }
          submitted.value = false;
        });
    }
  });
};

// 暴露方法
defineExpose({ initForm });
</script>
